/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Servlets;

import Classes.BusinessCase;
import Classes.CashCash;
import Classes.Immo;
import Classes.ShoppingChart;
import DAO.BusinessCaseDAO;
import DAO.ImmoDAO;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 *
 * @author alexander
 */
public class BuyManager extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
       

        String absender = request.getParameter("absender");
        int rechnungID = 0;
        
        if (absender.equalsIgnoreCase("immoDetail.jsp")){
            
            String immoID = request.getParameter("immoID");
            int immoIDAsInteger = Integer.parseInt(immoID);
            
            System.out.println("Warenkorb");
            
            HttpSession session = request.getSession(false);
            ShoppingChart basket = (ShoppingChart)session.getAttribute("sessionBasket");
            Vector<Immo> immoBasket = basket.getImmoInTheBasket();
            ImmoDAO newImmoDAO = new ImmoDAO();
            //System.out.println("Basket Before: "+immoBasket.size());
            Immo newImmo = new Immo();
            Vector<Immo> newImmoBasket = new Vector<Immo>();
            
            List<Integer> newList = new ArrayList<Integer>();
           
            if(immoBasket.size()<=0){
                immoBasket.add(newImmoDAO.getImmo(immoID));
            }
            
            if(immoBasket.size()>0){
                
                Iterator basketIterator = immoBasket.iterator();
                
                while(basketIterator.hasNext()){
                    Immo newImmo2 = new Immo();
                    newImmo2=(Immo)basketIterator.next();
                    newImmo2.getImmoID();
                    newList.add(newImmo2.getImmoID());                    
                }
                
            if(!newList.contains(immoIDAsInteger)){
                immoBasket.add(newImmoDAO.getImmo(immoID));
            }
                
                
            }
            
            /*
            Iterator iter007 = immoBasket.iterator();
            while(iter007.hasNext()){
                Immo aImmo = new Immo();
                aImmo = (Immo)iter007.next();
                if(aImmo.getImmoID()==immoIDAsInteger){
                    
                }
                else{
                    if(immoBasket.contains(newImmoDAO.getImmo(immoID))){}
                    else{newImmoBasket.add(newImmoDAO.getImmo(immoID));}   
                }
                
            }
            */
            System.out.println("Warenkorb="+immoBasket.size());          
            basket.setImmoInTheBasket(immoBasket);
            session.removeAttribute("sessionBasket");
            session.setAttribute("sessionBasket", basket);

            //System.out.println("Artikel im Warenkorb: "+newImmoBasket.size());
            getServletConfig().getServletContext().getRequestDispatcher("/myBasket.jsp").forward(request,response);

        }
        
        else {
           
            
            String userName = request.getParameter("userAlias");
            String userPwd = request.getParameter("userPwd"); 
            System.out.println("************************");
            System.out.println(userName);
            System.out.println(userPwd);
            System.out.println("************************");
            
            
            String numberOfImmosToBuyString  = request.getParameter("anzahlImmobilien");
            System.out.println("Anzahl der ausgewählten Immobilien: "+numberOfImmosToBuyString);
            int numberOfImmo = Integer.parseInt(numberOfImmosToBuyString);
            double  summeProvision = 0.00;
            int     summeImmoPrice = 0;
            Vector<String> bougthImmos = new Vector<String>();
            CashCash cash = new CashCash();

            
            String test = "";
            for(int i=1;i<=numberOfImmo;i++){
                //String immoident = "immo"+i;
                String immoIDToBuy = request.getParameter("immo"+i);
                if(immoIDToBuy!=null){
                        System.out.println("ImmoID to buy: "+immoIDToBuy);
                        //int immoIDToBuyTheImmo = Integer.parseInt(immoIDToBuy);

                        ImmoDAO newImmoDAO = new ImmoDAO();
                        Immo immoToBuy = newImmoDAO.getImmo(immoIDToBuy);
                        
                        double immoValue = immoToBuy.getPrice()+immoToBuy.getProvisionSum();
                        String debit = String.valueOf(immoValue);
                        
                        //@TODO Provision abbbuchen 
                        // -->  wenn cash cash postiv ist dann
                        // immoToBuy.getProvision
                        // immoToBuy.getPrice
                        // Abbuchen
                        // wenn positiv, dann 
                        //@TODO Zahlung abwickeln
                        
                        
                        //String pfadTruststore = 
                        //String pfadKeyStore = 
                        Properties p = System.getProperties();
                        
                        //p.remove("javax.net.ssl.keyStore");
                        //p.remove("javax.net.ssl.trustStore");                        

                        System.setProperty("javax.net.debug","all");  
                        
                        System.setProperty("javax.net.ssl.keyStore","keystore.ImportKey");
                        System.setProperty("javax.net.ssl.keyStorePassword","importkey");
                        System.setProperty("javax.net.ssl.trustStore","truststore"); 
                        System.setProperty("javax.net.ssl.trustStorePassword","0752765");  

                        File pfad = new File("");
                        System.out.print("----------> Pfad: ");
                        System.out.println(pfad.getAbsolutePath());
                        
                        HttpClient httpclient = new HttpClient();
                                              
                        //String requestURL="http://172.27.1.9/test_client.php?email=derbrandl@ovi.com&pwd=geheim&debit=886";
                        
                        String requestURL="https://172.27.1.8/ssl/debit.php?email=derbrandl@ovi.com&pwd=geheim&debit=953";
                        //String requestURL="https://172.27.1.8/ssl/debit.php";
                        PostMethod post = new PostMethod(requestURL);
                        
                        
                        
                        post.addParameter("email",userName);
                        post.addParameter("pwd",userPwd);
                        post.addParameter("debit",debit);
                       
                        httpclient.executeMethod(post);
                        
                        //httpclient.executeMethod(post);
                        
                        String response2 = post.getResponseBodyAsString(); 
                        
                        System.out.println(response2);
                        
                        //XML type = new XML();
                      
                        //post.releaseConnection();
                        

                        immoToBuy.setIsSold(true);
                        newImmoDAO.updateImmo(immoIDToBuy);
                        bougthImmos.add(newImmoDAO.getImmo(immoIDToBuy).getImmoHeadline());
                        summeProvision+=newImmoDAO.getImmo(immoIDToBuy).getProvisionSum();
                        summeImmoPrice+=newImmoDAO.getImmo(immoIDToBuy).getPrice();
                        
                        if (cash.verrechnen()){
                       
                       /*     
                        int port = 443;
                            
                        String hostName = "https://cashcash.ebusiness.univie.ac.at/ssl/debit.php";
                        SSLSocketFactory sslFact = (SSLSocketFactory) SSLSocketFactory.getDefault();
                        SSLSocket socket = (SSLSocket) sslFact.createSocket( hostName, port );
                        InputStream  in  = socket.getInputStream();
                        OutputStream out = socket.getOutputStream();

                        
                        */
                            
                            
                            
                        BusinessCase newBusinessCase = new BusinessCase();

                        newBusinessCase.setBuyerID(Integer.parseInt(request.getParameter("buyer")));
                        newBusinessCase.setImmoID(immoToBuy.getImmoID());
                        SimpleDateFormat s = new SimpleDateFormat("yyyyMMddHHmmssSS");
                        Date d = new Date();
                        String timeStamp = s.format(d);
                        newBusinessCase.setTimestamp(timeStamp);

                        BusinessCaseDAO newBusinessCaseDAO = new BusinessCaseDAO();
                        newBusinessCaseDAO.saveBusinessCase(newBusinessCase);
                        rechnungID = newBusinessCase.getCaseID();
                        test = "hallo";
                        }
                        else {
                        
                        System.out.println("CashCahs verweigert die Zahlung");
                        
                        }
                        
                        //Verkauf abgeschlossen//
                        
                        HttpSession session = request.getSession(false);
                        ShoppingChart sessionBasket = (ShoppingChart)session.getAttribute("sessionBasket");
                        Vector<Immo> immoBasket = sessionBasket.getImmoInTheBasket();
                        Vector<Immo> newImmoBasket = new Vector<Immo>();
                        
                        Iterator immoBasketIter = immoBasket.iterator();
                
                        while(immoBasketIter.hasNext()){
                            Immo newImmo = (Immo)immoBasketIter.next();
                            if(!(newImmo.getImmoID()==immoToBuy.getImmoID()))
                                newImmoBasket.add(newImmo);
                        }
                        

                        sessionBasket.setImmoInTheBasket(newImmoBasket);
                        session.setAttribute("sessionBasket", sessionBasket);
                
                }
                
                
                
            }
            
            
            System.out.println("Wir sehen, jetzt kaufen wir wirklich .... ");
            System.out.println("Echter Verkauf");
            
            
            //Erfolreiche Abbuchung anzeigen.... 
            //response.sendRedirect("index.jsp");      
            request.setAttribute("rechnungID", rechnungID);
            request.setAttribute("test",test);
            request.setAttribute("gekaufteImmos", bougthImmos);
            request.setAttribute("summeProvision",summeProvision);
            request.setAttribute("summePrice", summeImmoPrice);
            RequestDispatcher rd = request.getRequestDispatcher("rechnung.jsp"); 
            rd.forward(request,response);


        
        }        
        

    }}


